//
//  XGStatusListViewModel.swift
//  TodayNews
//
//  Created by monkey on 2020/2/23.
//  Copyright © 2020 itcast. All rights reserved.
//

import SwiftyJSON

/* 最新接口
private let KRetweetStatusURL: String = "https://api3-normal-c-lf.snssdk.com/api/feed/profile/v1/?client_extra_params=%7B%22playparam%22:%22codec_type:1%22%7D&count=20&stream_api_version=88&version_code=7.6.0&tma_jssdk_version=1.51.1.2&app_name=news_article&vid=3C5E8D31-76EA-4644-B837-DE5B40D5B0AA&channel=App%20Store&aid=13&update_version_code=76014&idfv=3C5E8D31-76EA-4644-B837-DE5B40D5B0AA&ac=WIFI&os_version=13.3.1&ssmix=a&device_platform=iphone&ab_client=a1,f2,f7,e1&device_type=iPhone%206S&idfa=FC7A7B37-88A0-49B5-BC0F-B1BE7E5E003C"
let parameters: [String: Any] = ["category": category,
                                 "visited_uid": userId,
                                 "iid": TodayNews_iid,
                                 "device_id": TodayNews_Device_Id,
                                 "offset": offset]
 */

class XGStatusListViewModel
{
    /// 获取用户动态数据
    /// - Parameters:
    ///   - type: 动态类型
    ///   - userId: 用户id
    ///   - isLoadMore: 是否加载更多
    ///   - completionHandle: 完成回调
    func fetchUserStatusList(type: XGTopTabType,userId: UInt64, isLoadMore: Bool, completionHandle: @escaping(Bool,Bool) -> Void) -> Void
    {
        switch type {
        case .article, .dongtai, .video, .column:
            fetchDongTaiList(userId: userId, completionHandle: completionHandle)
        case .wenda:
            fetchWenDaList(userId: userId, isLoadMore: isLoadMore, completionHandle: completionHandle)
        default:
            break
        }
    }
    
    func statusViewModelForIndex(_ index: Int) -> XGStatusViewModel
    {
        return statusList[index]
    }
    
    /// 注册cell
    /// - Parameters:
    ///   - tableView: tableView
    ///   - type: 动态类型
    func registerCell(tableView: UITableView, type: XGTopTabType) -> Void
    {
        switch type {
        case .article, .dongtai, .video, .column:
            tableView.xg_registerCell(cellType: XGStatusPostContentTableViewCell.self)
            tableView.xg_registerCell(cellType: XGStatusPostArticleTableViewCell.self)
            tableView.xg_registerCell(cellType: XGStatusReferenceContentTableViewCell.self)
        case .wenda:
            tableView.xg_registerCell(cellType: XGAnswerQuestionTableViewCell.self)
        default:
            break
        }
    }
    
    /// 返回动态数量
    /// - Parameter type: 动态类型
    func numberOfRowsInSection(type: XGTopTabType) -> Int
    {
        switch type {
        case .article, .dongtai, .video, .column:
            return statusList.count
        case .wenda:
            return answerQuestionList.count
        default:
            return 0
        }
    }
    
    /// 返回cell
    /// - Parameters:
    ///   - tableView: tableView
    ///   - indexPath: indexPath
    ///   - type: 动态类型
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, type: XGTopTabType) -> UITableViewCell
    {
        switch type {
        case .article, .dongtai, .video, .column:
            var cell: XGBaseStatusTableViewCell?
            let statusViewModel = statusList[indexPath.row]
            switch statusViewModel.statusType {
            case .postContent:
                cell = tableView.xg_dequeueReusableCell(indexPath: indexPath) as XGStatusPostContentTableViewCell
            case .postArticleOrVideo,.answerQuestion,.proposeQuestion:
                cell = tableView.xg_dequeueReusableCell(indexPath: indexPath) as XGStatusPostArticleTableViewCell
            case .commentOrQuoteContent,.commentOrQuoteOthers:
                cell = tableView.xg_dequeueReusableCell(indexPath: indexPath) as XGStatusReferenceContentTableViewCell
            default:
                cell = tableView.xg_dequeueReusableCell(indexPath: indexPath) as XGStatusPostContentTableViewCell
            }
            cell?.statusViewModel = statusList[indexPath.row]
            return cell!
        case .wenda:
            let cell = tableView.xg_dequeueReusableCell(indexPath: indexPath) as XGAnswerQuestionTableViewCell
            cell.answerQuestionViewModel = answerQuestionList[indexPath.row]
            return cell
        default:
            return UITableViewCell()
        }
    }
        
    /// 返回cell行高
    /// - Parameters:
    ///   - tableView: tableView
    ///   - indexPath: indexPath
    ///   - type: 动态类型
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath, type: XGTopTabType) -> CGFloat
    {
        switch type {
        case .article, .dongtai, .video, .column:
            return statusList[indexPath.row].rowHeight
        case .wenda:
            return answerQuestionList[indexPath.row].rowHeight
        default:
            return 0
        }
    }

    /// 加载用户动态数据
    /// - Parameters:
    ///   - userId: 用户id
    ///   - completionHandle: 完成回调
    private func fetchDongTaiList(userId: UInt64, completionHandle: @escaping(Bool,Bool) -> Void) -> Void
    {
        let url = TodayNews_Base_URL + "dongtai/list/v15/"
        let parameters: [String: Any] = ["user_id": userId,
                      "max_cursor": dongTaiCursor,
                      "device_id": TodayNews_Device_Id,
                      "iid": TodayNews_iid]
        AlamofireTool.request(method: .get, urlString: url, parameters: parameters) { (responseObject, error) in
            if responseObject == nil || error != nil {
                XGPrint("加载用户动态列表失败!")
                completionHandle(false,false)
                return
            }

            let jsonObject = JSON(responseObject!)
//            try? jsonObject.rawData().write(to: URL(fileURLWithPath: "/Users/monkey/Desktop/1.data"))
            let hasMore = jsonObject["data"]["has_more"].bool ?? false // 是否还有数据
            self.dongTaiCursor = jsonObject["data"]["max_cursor"].uInt64 ?? 0 // 记录动态偏移量
            let dataArray = jsonObject["data"]["data"].array
            let statusModels = dataArray?.compactMap({ XGStatusModel.deserialize(from: $0.dictionaryObject)})
            DispatchQueue.global().async {
                self.statusList += statusModels?.compactMap({XGStatusViewModel(statusModel: $0)}) ?? []
                DispatchQueue.main.async {
                    completionHandle(true,hasMore)
                }
            }
        }
    }
    
    /// 加载用户问答数据
    /// - Parameters:
    ///   - userId: 用户id
    ///   - isLoadMore: 是否加载更多
    ///   - completionHandle: 完成回调
    private func fetchWenDaList(userId: UInt64, isLoadMore: Bool, completionHandle: @escaping(Bool,Bool) -> Void) -> Void
    {
        // 判断是否是加载更多
        let url = TodayNews_Base_URL + (isLoadMore ? "wenda/profile/wendatab/loadmore/" : "wenda/profile/wendatab/brow/")
        var parameters: [String: Any] = ["other_id": userId,
                      "format": "json",
                      "device_id": TodayNews_Device_Id,
                      "iid": TodayNews_iid]
        if isLoadMore {
            parameters["cursor"] = wenDaCursor
        }
        AlamofireTool.request(method: .get, urlString: url, parameters: parameters) { (responseObject, error) in
            if responseObject == nil || error != nil {
                XGPrint("加载用户问答数据失败!")
                completionHandle(false,false)
                return
            }
            
            let jsonObject = JSON(responseObject!)
            let hasMore = (jsonObject["has_more"].int ?? 0) == 1  // 是否还有数据
            self.wenDaCursor = jsonObject["cursor"].string ?? ""  // 记录问答偏移量
            let answerQuestionArray = jsonObject["answer_question"].array
            let models = answerQuestionArray?.compactMap({ return XGAnswerQuestionModel.deserialize(from: $0.dictionaryObject)})
            DispatchQueue.global().async {
                self.answerQuestionList += models?.compactMap({XGAnswerQuestionViewModel(answerQuestionModel: $0)}) ?? []
                DispatchQueue.main.async {
                    completionHandle(true,hasMore)
                }
            }
        }
    }
    
    // MARK: - 私有属性
    
    /// 偏移量 用来加载动态更多数据
    private var dongTaiCursor: UInt64 = 0
    /// 偏移量 用来加载问答更多数据
    private var wenDaCursor: String = ""
    /// 动态列表
    private var statusList = [XGStatusViewModel]()
    /// 问答列表
    private var answerQuestionList = [XGAnswerQuestionViewModel]()
}
